package edu.whu.webgis.server;


import edu.whu.webgis.entity.Message;
import edu.whu.webgis.service.IMessageService;
import edu.whu.webgis.utils.ServerEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import static java.rmi.server.LogStream.log;

/**
 * @author zfChen
 * @create 2022/11/14 15:11
 */
@ServerEndpoint(value="/websocket/{userId}",encoders={ServerEncoder.class})
@Component
@Slf4j
public class WebSocketServer {
    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全集合，也可以map改成set，用来存放每个客户端对应的MyWebSocket对象。*/
    public static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId= "";

    @Autowired
    IMessageService messageService;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;

        if(!webSocketMap.containsKey(userId)){
            //加入集合中
            webSocketMap.put(userId,this);
            //在线数加1
            addOnlineCount();
        }
        WebSocketServer.log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从集合中删除
            subOnlineCount();
        }
        WebSocketServer.log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        WebSocketServer.log.info("【websocket消息】收到客户端发来的消息:{}", message);
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        WebSocketServer.log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessageObject(Message message) throws IOException, EncodeException {
        this.session.getBasicRemote().sendObject(message);
    }


    /**
     * 发送自定义消息
     * */
    public void sendInfo(Message message) {
        WebSocketServer.log.info("接收到:"+message.getUid()+"的消息:"+message.getContent());
        messageService.sendMessage(message);
        for (String key : webSocketMap.keySet()) {
            if (!key.equals(message.getUid())) {
                try {
                    WebSocketServer.log.info("发送消息到:"+key+",消息:"+message.getContent());
                    webSocketMap.get(key).sendMessageObject(message);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

//        if(webSocketMap.containsKey(uid)){
//            webSocketMap.get(userId).sendMessage(message);
//        }else{
//            log.error("用户"+userId+",不在线！");
//        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}


